﻿using UnityEngine;
using System;
using System.Linq;
using System.Collections;

using Hont;

namespace Hont.AStar
{
    public class HontAStarUnityOCTTreeSyncer : IOCTNodeSyncer<Position>
    {
        HontAStarUnity mAStarUnity;


        public HontAStarUnityOCTTreeSyncer(HontAStarUnity astarUnity)
        {
            this.mAStarUnity = astarUnity;
        }

        public void Sync(OCTNode<Position> node)
        {
            if (!node.UserDataDict.ContainsKey(HontAStarUnity.OCTTREEUSERDATA_HAS_WALKABLE_BOX))
                node.UserDataDict.Add(HontAStarUnity.OCTTREEUSERDATA_HAS_WALKABLE_BOX, false);

            var hasWalkableBox = (bool)node.UserDataDict[HontAStarUnity.OCTTREEUSERDATA_HAS_WALKABLE_BOX];

            if (node.Items.Count > 0)
            {
                hasWalkableBox = node.Items.Count(m => mAStarUnity.Grid.GetIsWalkable(m.Value)) > 0;
            }
            else
            {
                hasWalkableBox = node.Childrens.Any(m =>
                {
                    object value = null;
                    if (m.UserDataDict.TryGetValue(HontAStarUnity.OCTTREEUSERDATA_HAS_WALKABLE_BOX, out value))
                        return (bool)value;
                    else
                        return false;
                });
            }

            node.UserDataDict[HontAStarUnity.OCTTREEUSERDATA_HAS_WALKABLE_BOX] = hasWalkableBox;
        }
    }
}
